<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2017/6/5
 * Time: 上午9:38
 */

namespace app\apiagent\controller;

use app\common\controller\ActionLogs;
use app\common\controller\Platinfo;
use app\common\model\Agent;
use app\common\model\Merchant;
use think\Config;

class Api
{
    public function api()
    {
        try {
//            $data['return_code'] = "FAIL";
//            $data['result_code'] = "FAIL";
//            $data['result_msg'] = "系统升级中请稍后再试";
//            $data['return_msg'] = "系统升级中请稍后再试";
//            return json($data);
//            return json_encode($data);
            $postData = file_get_contents('php://input');
            if ($postData) {
                $encode = mb_detect_encoding($postData, array("ASCII", 'UTF-8', "GB2312", "GBK", 'BIG5'));
                $postData = mb_convert_encoding($postData, "UTF-8", $encode);

                if (is_json($postData)) {
                    $param1 = json_decode($postData, true);
                    $query_type = $param1['method'];
                    $param = json_decode($postData, true);
                    $check = $this->checkparam(array_keys($param), $query_type);
                    if (isset($param['merchantid'])) {
                        $s = $this->checkappid($param['appid'], $param['merchantid']);
                        if ($s == "FAIL") {
                            $data['return_code'] = "FAIL";
                            $data['result_code'] = "FAIL";
                            $data['result_msg'] = "appid与merchantid不匹配";
                            $data['return_msg'] = "appid与merchantid不匹配";
                            return json_encode($data);
                        }

                    }

                    if ($check['code'] == "0") {
                        unset($param1['sign']);
                        $sign = getsign(uni_array($param1), "MD5", $param['appid']);
//                        if ($param['merchantid']=='501'){
//                            $CardsThree = new CardsThree();
//                            $sign = $CardsThree->getsign(uni_array($param1), "MD5", $param['appid']);
//                        }else{
//                            $sign = getsign(uni_array($param1), "MD5", $param['appid']);
//                        }
                        if ($sign == $param['sign']) {
                            $data = $this->api_query($param);

                        } else {
                            $data['return_code'] = "SUCCESS";
                            $data['result_code'] = "FAIL";
                            $data['result_msg'] = "签名错误";
                            $data['return_msg'] = "签名错误" . $sign;
                        }
                    } else {
                        $data['return_code'] = "SUCCESS";
                        $data['result_code'] = "FAIL";
                        $data['result_msg'] = $check['message'];
                        $data['return_msg'] = $check['message'];
                    }
                } else {
                    $data['return_code'] = "FAIL";
                    $data['result_code'] = "FAIL";
                    $data['result_msg'] = "数据格式错误";
                    $data['return_msg'] = "请传递正确的数据格式";
                }
            } else {
                $data['return_code'] = "FAIL";
                $data['result_code'] = "FAIL";
                $data['result_msg'] = "数据格式错误";
                $data['return_msg'] = "请传递正确的数据格式";
            }
        } catch (\Exception $e) {
            $data['return_code'] = "FAIL";
            $data['result_code'] = "FAIL";
            $data['result_msg'] = "系统错误";
            $data['return_msg'] = "系统错误" . $e->getMessage();
        }
        return json_encode($data);


    }


    //检查登陆账号代理商是否正常
    private function check_agent($param){
        //所属平台信息
        $Platinfo = new Platinfo();
        $plat_info = $Platinfo->getagentinfo('mid', $param['merchantid']);
        //此代理商是否被停用
        if ($plat_info['agent_id'] == 24 || $plat_info['agent_id'] == 28 || $plat_info['agent_id'] == 32){
//            $res_data['code'] = "FAIL";
            $res_data['code'] = "SUCCESS";
//            $res_data['code'] = 1;
        }else{
            $res_data['code'] = "SUCCESS";
        }
        return $res_data;
    }

    private function checkparam($param, $type)
    {
        switch ($type) {

            /*
            * 代理商的申请及商户、门店的申请
            *
            */
            //申请代理商
            case "apply_agent":
                $sdata = array('method', 'source', 'device_id', 'source', 'version', 'timestamp', 'company_name','realname','mobile','address','open_url','component_appid','component_appsecret','component_encodingaeskey','component_token','requestdomain','wsrequestdomain','uploaddomain','downloaddomain','webviewdomain','wx_pay_appid','wx_pay_appsecret','wx_pay_partnerid','wx_pay_partnerkey','apiclient_key','apiclient_cert','apiclient_rootca','sysid');
                break;
            //申请商户
            case "apply_momach":
                $sdata = array('method', 'source', 'device_id', 'source', 'version', 'timestamp', 'company_name','realname','mobile','address','wx_pay_partnerid','agentid','service_charge','momach_type');
                break;
            //添加门店
            case "add_mach":
                $sdata = array('method', 'source', 'device_id', 'source', 'version', 'timestamp', 'top_mach_no','merchant','sub_mch_id');
                break;
            //修改门店
            case "edit_mach":
                $sdata = array('method', 'source', 'device_id', 'source', 'version', 'timestamp', 'signaturenonce','mach_no','merchant','sub_mch_id');
                break;
            //删除门店
            case "del_mach":
                $sdata = array('method', 'source', 'device_id', 'source', 'version', 'timestamp', 'signaturenonce','mach_no');
                break;
            //END
            default:
                $sdata['code'] = "(无)";
                $sdata['message'] = "请求的方法不存在";
                break;

        }

        $arr = array_diff($sdata, $param);
        $arr2 = implode(',', $arr);

        if (!empty($arr2)) {
            $arrs['code'] = "FAIL";
            $arrs['message'] = "缺少参数" . $arr2;
        } else {
            $arrs['code'] = "0";
            $arrs['message'] = "SUCCESS";

        }
        return $arrs;
    }

    public function api_query($array)
    {
        try {

            $type = $array['method'];
            switch ($type) {
                /*
                * 代理商的申请及商户、门店的申请
                *
                */
                //申请代理商
                case "apply_agent":
                    $data = action('api/ApplyAgents/apply_agent', array($array));
                    break;
                //申请商户
                case "apply_momach":
                    $data = action('api/ApplyAgents/apply_momach', array($array));
                    break;
                //添加门店
                case "add_mach":
                    $data = action('api/ApplyAgents/add_mach', array($array));
                    break;
                //修改门店
                case "edit_mach":
                    $data = action('api/ApplyAgents/edit_mach', array($array));
                    break;
                //删除门店
                case "del_mach":
                    $data = action('api/ApplyAgents/del_mach', array($array));
                    break;
                //END
                default:
                    $data['return_code'] = "SUCCESS";
                    $data['result_code'] = "FAIL";
                    $data['result_msg'] = "错误的方法";
                    $data['return_msg'] = "错误的方法";
            }
        } catch (\Exception $e) {
            $data['return_code'] = "SUCCESS";
            $data['result_code'] = "FAIL";
            $data['result_msg'] = "系统错误";
            $data['return_msg'] = "系统错误" . $e->getMessage();
        }
        $data['version'] = "2.0.0";
        $data['timestamp'] = time();
        $data['signaturenonce'] = MD5(rand(1000000, 9999999));
        $data['sign'] = getsign(uni_array($data), "MD5", $array['appid']);
        $logs['type'] = "apilog";
        $logs['up'] = $array;
        $logs['down'] = $data;
        trace("api_query：" . json_encode($logs, 256), 'SysRunLog');
        return $data;
    }

    //判断appid是否与merchantid匹配
    private function checkappid($appid, $merchantid)
    {
        $map['sign_appid'] = $appid;
        $Agent = new Agent();
        $Agents = $Agent->where($map)->field('id')->select();
        foreach ($Agents as $k => $v) {
            $agentid[] = $v['id'];
        }
        $sid = implode(',', $agentid);
        $mab['agent'] = array('in', $sid);
        $mab['id'] = $merchantid;
        $Merchant = new Merchant();
        $mach = $Merchant->where($mab)->find();
        if ($mach) {
            return "SUCCESS";
        } else {
            return "FAIL";
        }


    }


}